<template>
  <div class="add-qrcode">
    <div class="container" v-loading="loading">
      <div class="code-title text-overflow">创建台码</div>
      <div class="code-container">
        <div class="filter-box">
          <div>
            <el-input v-model="filter.platformCode" placeholder="请输入台码"></el-input>
          </div>
          <div>
            <el-input v-model="filter.agent" placeholder="请输入代理商手机号"></el-input>
          </div>
          <div>
            <el-date-picker
              style="width:140px"
              v-model="filter.startTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="date"
              placeholder="开始日期"
            ></el-date-picker>
          </div>
          <div>
            <el-date-picker
              style="width:140px"
              v-model="filter.endTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="date"
              placeholder="结束日期"
            ></el-date-picker>
          </div>
          <div>
            <el-select v-model="filter.state" clearable>
              <el-option
                v-for="item in stateList"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </div>
          <div style="width:150px">
            <el-button type="primary" @click="handleQuery">筛选</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
        
        <div class="code-list">
          <el-table
            ref="multipleTable"
            :data="qrcodeList"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" :selectable="handleDisabled" width="55"></el-table-column>
            <el-table-column
              v-for="item in tableHeader"
              :key="item.prop"
              :prop="item.prop"
              :label="item.label"
              :formatter="formatterList"
            ></el-table-column>
            <el-table-column fixed="right" label="操作" width="80">
              <template slot-scope="scope">
                <el-button @click="handleLookcode(scope.row)" type="text">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="operate-box">
          <el-button @click="handleCreateCode">创建台码</el-button>
          <el-button @click="handleBatch">批量拨码</el-button>
          <el-button @click="handleExport">批量导出二维码</el-button>
        </div>
        <div class="pages-control">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="pages.currentPage"
            :page-size="pages.page_size"
            layout="total, prev, pager, next"
            :total="pages.total"
          ></el-pagination>
        </div>
        
      </div>
    </div>
    <!-- 创建台码的dailog -->
    <el-dialog title="创建台码" :visible.sync="dialogVisible" width="50%">
      <div>
        <span>台码类型：</span>
        <el-select v-model="createInfo.type">
          <el-option
            v-for="item in createTypes"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          ></el-option>
        </el-select>
      </div>
      <br>
      <div>
        <span>台码数量：</span>
        <el-input-number
          v-model="createInfo.count"
          :min="1"
          @blur="handleCreateCode"
          :max="100"
          :step="5"
        ></el-input-number>
      </div>
      <br>
      <div>
        <span>生成编号：</span>
        <span>{{tempPlatformCode.startNumber}}</span> -
        <span>{{tempPlatformCode.endNumber}}</span>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCreateCode">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 批量拨码dailog -->
    <el-dialog title="批量拨码" :visible.sync="dialogVisible2" width="50%">
      <div>
        <el-input placeholder="请输入拨码的代理商" v-model="batchInfo.phone"></el-input>
      </div>
      <br>
      <div>
        <span>已选台码：</span>
        <span v-html="batchInfo.count"></span>
      </div>
      <br>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatch">确 定</el-button>
        <el-button @click="dialogVisible2 = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 台码查看 -->
    <el-dialog title="查看台码" :visible.sync="dialogVisible4" width="600px">
      <div style="text-align:center">
        <img width="350px" height="350px" :src="previewCodeUrl" alt="台码加载失败！">
      </div>
      <div style="text-align:center">
        <span v-html="previewCode"></span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button style="width:100px" type="primary" @click="handleDownloadQrcode">下 载</el-button>
        <el-button style="width:100px" @click="dialogVisible4 = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
function download(url, name) {
  const aLink = document.createElement("a");
  aLink.download = name;
  aLink.href = url;
  aLink.dispatchEvent(new MouseEvent("click", {}));
}
function downloadFile(url) {
  try {
    var elemIF = document.createElement("iframe");
    elemIF.src = url;
    elemIF.style.display = "none";
    document.body.appendChild(elemIF);

    setTimeout(function() {
      document.body.removeChild(elemIF);
    }, 3000);
  } catch (e) {}
}

export default {
  name: "add-qrcode",
  data() {
    return {
      loading: false,
      allcheck: false,
      dialogVisible: false,
      dialogVisible2: false,
      dialogVisible4: false,
      previewCodeUrl: "",
      previewCode: "",
      selectedList: [],
      stateList: [
        { label: "未绑定", value: "0" },
        { label: "未激活", value: "1" },
        { label: "已激活", value: "2" }
      ],
      tempPlatformCode: {
        startNumber: "",
        endNumber: ""
      },
      createTypes: [{ value: "1", label: "商户台码" }],
      filter: {
        platformCode: "",
        agent: "", // 手机号
        startTime: "",
        endTime: "",
        state: ""
      },
      createInfo: {
        count: 10,
        type: "1"
      },
      batchInfo: {
        phone: "",
        count: 0
      },
      qrcodeList: [],
      tableHeader: [
        { prop: "platformCode", label: "台卡卡号" },
        { prop: "platformType", label: "卡片类型" },
        { prop: "agent", label: "所属代理商" },
        { prop: "shopId", label: "所属商户" },
        { prop: "dialCodeType", label: "拨码状态" },
        { prop: "state", label: "状态" },
        { prop: "createTime", label: "创建时间" },
        { prop: "createBy", label: "创建人" }
      ],
      pages: {
        total: 10,
        page_size: 20,
        currentPage: 1
      }
    };
  },
  components: {},
  created() {
    this.handleQuery();
  },
  mounted() {},
  methods: {
    handleSelectionChange(val) {
      this.selectedList = val;
    },
    handleDisabled(row, index) {
      return row.dialCodeType !== "1";
    },
    handleCurrentChange(value) {
      // 分页器控制
      this.handleQuery();
    },
    handleLookcode(cell) {
      // 查看台码
      this.dialogVisible4 = true;
      this.previewCodeUrl = cell.qrcCode;
      this.previewCode = cell.platformCode;
    },
    handleDownloadQrcode() {
      // 下载预览的台码
      let name = this.previewCode + ".jpg";
      download(this.previewCodeUrl, name);
    },
    handleSubmitExport() {
      // 导出操作
      this.dialogVisible3 = false;
      let arrType = this.exportInfo.type;
      let arrCode = this.selectedList.map(item => item.platformCode).join(",");
      let platformCode = this.filter.platformCode;
      let staTime = this.filter.startTime;
      let endTime = this.filter.endTime;
      let agent = this.filter.agent;
      let token = sessionStorage.getItem(1);
      let url = `user/app/Platform/export/${token}`;
      let params = `platformCode=${platformCode}&staTime=${staTime}&endTime=${endTime}&agent=${agent}&arrType=${arrType}&arrCode=${arrCode}`;
      params = encodeURI(params);
      this.$Http
        .post(url, params, {
          responseType: "blob"
        })
        .then(res => {
          //   this.$Http.download(res);
          let blob = res.data;
          let reader = new FileReader();
          reader.readAsDataURL(blob);
          reader.onload = e => {
            let a = document.createElement("a");
            a.download = "info.xlsx";
            a.href = e.target.result;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
          };
        })
        .catch(err => {
          this.$notify({
            title: "温馨提示",
            message: "导出信息失败！",
            type: "warning"
          });
        });
    },
    handleExport() {
      if (this.selectedList.length === 0) {
        this.$notify({
          title: "温馨提示",
          message: "请至少选择一条数据导出！",
          type: "warning"
        });
        return;
      }
      let dialCode = this.selectedList.map(item => item.platformCode).join(",");
      let token = sessionStorage.getItem(1);
      let url = `user/app/Platform/exportImg/${token}`;
      let params = `dialCode=${dialCode}`;
      this.$Http
        .post(url, params)
        .then(res => {
          if (res.data.resp_code === "000000") {
            downloadFile(res.data.result);
          } else {
            this.$notify({
              title: "温馨提示",
              message: res.data.resp_message,
              type: "warning"
            });
          }
        })
        .catch(err => {
          this.$notify({
            title: "温馨提示",
            message: "导出信息失败！",
            type: "warning"
          });
        });
    },
    handleReset() {
      this.filter.platformCode = "";
      this.filter.startTime = "";
      this.filter.endTime = "";
      this.filter.agent = "";
      this.filter.state = "";
      this.handleQuery();
    },
    handleQuery() {
      let platformCode = this.filter.platformCode;
      let staTime = this.filter.startTime;
      let endTime = this.filter.endTime;
      let agent = this.filter.agent;
      let state = this.filter.state;
      let token = sessionStorage.getItem(1);
      let url = `user/app/Platform/queryPlatformPagerlist/${token}?pageNumber=${
        this.pages.currentPage
      }&state=${state}&platformCode=${platformCode}&staTime=${staTime}&endTime=${endTime}&agent=${agent}`;
      url = encodeURI(url);
      this.loading = true;
      this.$Http
        .get(url, "")
        .then(res => {
          this.loading = false;
          if (res.data.resp_code === "000000") {
            this.pages.total = res.data.count;
            this.qrcodeList = res.data.result;
          } else {
            this.$notify({
              title: "温馨提示",
              message: res.data.resp_message,
              type: "warning"
            });
          }
        })
        .catch(err => {
          this.loading = false;
          this.$notify({
            title: "温馨提示",
            message: "获取台卡列表失败！",
            type: "warning"
          });
        });
    },
    handleCreateCode() {
      // 生成台码
      if (this.createInfo.count > 100 || this.createInfo.count < 1) {
        this.$notify({
          title: "温馨提示",
          message: "一次创建的数量不能少于1且不能超过100",
          type: "warning"
        });
        return;
      }
      this.loading = true;
      let token = sessionStorage.getItem(1);
      let url = `user/app/Platform/savePlatform/${token}`;
      let params = `type=2&platformNumber=${this.createInfo.count}`;
      this.$Http
        .post(url, params)
        .then(res => {
          this.loading = false;
          if (res.data.resp_code === "000000") {
            this.tempPlatformCode = res.data.result;
            this.dialogVisible = true;
          } else {
            this.$notify({
              title: "温馨提示",
              message: res.data.resp_message,
              type: "warning"
            });
          }
        })
        .catch(err => {
          this.loading = false;
          this.$notify({
            title: "警告",
            message: "获取创建台码id失败！",
            type: "warning"
          });
        });
    },
    submitCreateCode() {
      // 提交台码编号，生成台码
      this.loading = true;
      this.dialogVisible = false;
      let token = sessionStorage.getItem(1);
      let url = `user/app/Platform/savePlatform/${token}`;
      let params = `type=1&platformNumber=${
        this.createInfo.count
      }&platformType=${this.createInfo.type}`;
      this.$Http
        .post(url, params)
        .then(res => {
          this.loading = false;
          if (res.data.resp_code === "000000") {
            this.dialogVisible = false;
            this.$notify({
              title: "温馨提示",
              message: res.data.resp_message,
              type: "success"
            });
            this.handleQuery();
          } else {
            this.$notify({
              title: "温馨提示",
              message: res.data.resp_message,
              type: "warning"
            });
          }
        })
        .catch(err => {
          this.loading = false;
          this.$notify({
            title: "警告",
            message: "获取创建台码失败！",
            type: "warning"
          });
        });
    },
    handleBatch() {
      // 批量拨码
      // 提交拨码信息

      this.batchInfo.count = 0;
      this.batchInfo.count = this.selectedList.length;
      if (this.batchInfo.count === 0) {
        this.$notify({
          title: "温馨提示",
          message: "请先勾选台码！",
          type: "warning"
        });
        return;
      }
      this.dialogVisible2 = true;
    },
    submitBatch() {
      if (this.batchInfo.phone == "" || this.batchInfo.phone == null) {
        this.$notify({
          title: "温馨提示",
          message: "请先填写代理商手机号！",
          type: "warning"
        });
        return;
      }
      let l = this.selectedList.map(item => item.platformCode).join(",");
      this.dialogVisible2 = false;
      this.loading = true;
      let token = sessionStorage.getItem(1);
      let url = `user/app/Platform/batchDialCode/${token}`;
      let params = `agent=${this.batchInfo.phone}&dialCode=${l}`;
      params = encodeURI(params);
      this.$Http
        .post(url, params)
        .then(res => {
          this.loading = false;
          if (res.data.resp_code === "000000") {
            this.$notify({
              title: "温馨提示",
              message: res.data.resp_message,
              type: "success"
            });
            this.handleQuery();
          } else {
            this.$notify({
              title: "温馨提示",
              message: res.data.resp_message,
              type: "warning"
            });
          }
        })
        .catch(err => {
          this.loading = false;
          this.$notify({
            title: "警告",
            message: "拨码失败！",
            type: "warning"
          });
        });
    },
    handleStatus(status) {
      if (status === "0") {
        return "未绑定";
      }
      if (status === "1") {
        return "未激活";
      }
      if (status === "2") {
        return "已激活";
      }
      return status;
    },
    formatterList(row, column, cellValue, index) {
      //  格式化信息
      if (column.property === "platformType") {
        return cellValue == "1" ? "台卡" : "其他类型";
      } else if (column.property === "agent") {
        return cellValue ? cellValue : "暂无代理";
      } else if (column.property === "shopId") {
        return cellValue ? cellValue : "暂无商户";
      } else if (column.property === "dialCodeType") {
        return cellValue === "0" ? "未拨码" : "已拨码";
      } else if (column.property === "dialCodeType") {
        return cellValue === "0" ? "未拨码" : "已拨码";
      } else if (column.property === "state") {
        return this.handleStatus(cellValue);
      } else {
        return cellValue===null?'--':cellValue;
      }
    }
  }
};
</script>
<style scoped>
.container {
  border: 1px solid #ededed;
}
.code-title {
  height: 50px;
  line-height: 50px;
  font-size: 26px;
  color: #409eff;
  padding: 5px 20px;
  border-bottom: 1px solid #ededed;
}
.filter-box {
  padding: 20px;
  display: flex;
  justify-content: space-around;
  border-bottom: 1px solid #efefef;
}
.filter-box > div {
  min-width: 150px;
  box-sizing: border-box;
  padding: 0 10px;
  white-space: nowrap;
}
.code-list {
  min-height: 350px;
}
table {
  background-color: #fff;
  width: 100%;
  font-size: 12px;
  min-width: 900px;
}
th {
  position: relative;
  word-wrap: normal;
  text-overflow: ellipsis;
  vertical-align: middle;
  border-bottom: 1px solid #ebeef5;
}
thead {
  padding: 8px 0;
  color: #909399;
  background-color: #f5f7fa;
}
tr {
  padding: 8px 0;
}
tr:hover {
  background-color: #ccd2df;
}
td {
  border: none;
  border-bottom: 1px solid #ebeef5;
}
.table-cell {
  white-space: normal;
  word-break: break-all;
  line-height: 22px;
  padding: 10px 10px;
  text-align: center;
  min-width: 40px;
  box-sizing: border-box;
}
.pages-control {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
  border-top: 1px solid #ebeef5;
}
.code-activated {
  background-color: #f5f7fa;
}
.operate-box{
    padding: 16px;
}
</style>